<template>
  <el-cascader
    :props="props"
    placeholder="选择年段班级"
    :value="cascaderData"
    :ref="refKey"
    @change="handleDep()"
    clearable
  ></el-cascader>
</template>

<script>
import {sectionIndex, classIndex} from "@/api/admin/class"

export default {
  name: "chooseClass",
  props: {
    refKey: {
      type: String,
      default: 'classCom'
    },
    section_id: {
      type: Number,
      default: 0
    },
    class_id: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      cascaderData: [],
      props: {
        lazy: true,
        label: "name",
        value: "id",
        lazyLoad: this.lazyLoad,
      },
      sectionId: 0,
      classId: 0
    }
  },
  watch: {
    // section_id(){
    //   console.log('section_id:', this.section_id)
    //   this.cascaderData = [this.section_id , this.class_id]
    // }
  },
  created() {
    if (this.section_id) {
      this.cascaderData = [this.section_id, this.class_id]
    }
  },
  methods: {
    async lazyLoad(node, resolve) {
      console.log('node, resolve', node, resolve, this.cascaderData)
      let list = []
      if (!node.level) {
        let res = await sectionIndex({
          p: 1,
        });
        for (let item of res.list.data) {
          list.push({
            name: item.section_name,
            id: item.id
          })
        }
        resolve(list);
      } else {
        let res = await classIndex({
          p: 1,
          section_id: node.value
        });
        for (let item of res.list.data) {
          list.push({
            name: item.class_name,
            id: item.id,
            leaf: true
          })
        }
        resolve(list);
      }
    },
    handleDep(option) {
      if (this.$refs[this.refKey].getCheckedNodes()[0]) {
        let id_ = this.$refs[this.refKey].getCheckedNodes()[0].path;
        // let name_ = this.$refs["address"].getCheckedNodes()[0].pathLabels;
        console.log('id_:', id_)
        this.sectionId = id_[0]
        this.classId = id_[1]
      } else {
        this.sectionId = 0
        this.classId = 0
      }
      this.redeHander()
    },
    redeHander() {
      // if(this.section_id && this.class_id ){
      this.$emit('onChangeClass', {section_id: this.sectionId, class_id: this.classId, name: this.refKey});
      // }
    }
  }
}
</script>

<style scoped>

</style>
